<template>
  <div class="base-form">
    <el-form
      ref="formRef"
      :model="modelValue"
      :rules="rules"
      :label-width="labelWidth"
      :label-position="labelPosition"
      :label-suffix="labelSuffix"
      :inline="inline"
      :inline-message="inlineMessage"
      :status-icon="statusIcon"
      :disabled="disabled"
      :hide-required-asterisk="hideRequiredAsterisk"
      :require-asterisk-position="requireAsteriskPosition"
      :show-message="showMessage"
      :validate-on-rule-change="validateOnRuleChange"
      :size="size"
      @validate="handleValidate"
      @submit.prevent="handleSubmit"
    >
      <!-- 动态插槽 -->
      <template v-for="(_, name) in $slots" #[name]="slotData">
        <slot :name="name" v-bind="slotData || {}"></slot>
      </template>

      <!-- 默认操作按钮插槽 -->
      <slot name="actions" v-bind="{ loading, submitDisabled, handleSubmit, handleReset }">
        <div class="base-form__actions" v-if="showActions">
          <el-button @click="handleReset" :disabled="loading">
            重置
          </el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="loading"
            :disabled="submitDisabled"
          >
            {{ submitText }}
          </el-button>
        </div>
      </slot>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'

// 定义组件属性接口
interface BaseFormProps {
  // 表单数据
  modelValue: Record<string, any>

  // 验证规则
  rules?: FormRules

  // 布局配置
  labelWidth?: string | number
  labelPosition?: 'left' | 'right' | 'top'
  labelSuffix?: string
  inline?: boolean
  inlineMessage?: boolean
  statusIcon?: boolean
  disabled?: boolean
  hideRequiredAsterisk?: boolean
  requireAsteriskPosition?: 'left' | 'right'
  showMessage?: boolean
  validateOnRuleChange?: boolean
  size?: 'large' | 'default' | 'small'

  // 操作按钮配置
  showActions?: boolean
  submitText?: string
  submitDisabled?: boolean
  loading?: boolean

  // 验证配置
  validateOnSubmit?: boolean
}

// 定义组件事件
interface BaseFormEmits {
  (e: 'update:modelValue', value: Record<string, any>): void
  (e: 'validate', isValid: boolean, fields: any): void
  (e: 'submit', modelValue: Record<string, any>): void
  (e: 'reset'): void
}

// 默认属性
const props = withDefaults(defineProps<BaseFormProps>(), {
  rules: () => ({}),
  labelWidth: '100px',
  labelPosition: 'right',
  labelSuffix: '',
  inline: false,
  inlineMessage: false,
  statusIcon: false,
  disabled: false,
  hideRequiredAsterisk: false,
  requireAsteriskPosition: 'left',
  showMessage: true,
  validateOnRuleChange: true,
  size: 'default',
  showActions: true,
  submitText: '确定',
  submitDisabled: false,
  loading: false,
  validateOnSubmit: true
})

// 定义事件
const emit = defineEmits<{
  (e: 'update:modelValue', value: Record<string, any>): void
  (e: 'validate', isValid: boolean, fields: any): void
  (e: 'submit', modelValue: Record<string, any>): void
  (e: 'reset'): void
}>()

// 表单引用
const formRef = ref<FormInstance>()

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  (newValue) => {
    // 可以在这里添加表单数据变化的处理逻辑
  },
  { deep: true }
)

// 表单验证
const validate = async (): Promise<boolean> => {
  if (!formRef.value) return false

  try {
    const valid = await formRef.value.validate()
    emit('validate', valid, valid ? {} : {})
    return valid
  } catch (error) {
    console.warn('Form validation error:', error)
    return false
  }
}

// 验证指定字段
const validateField = async (prop: string | string[]): Promise<boolean> => {
  if (!formRef.value) return false

  try {
    await formRef.value.validateField(prop)
    return true
  } catch (error) {
    console.warn('Field validation error:', error)
    return false
  }
}

// 重置表单
const resetFields = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  emit('reset')
}

// 清除验证
const clearValidate = (props?: string | string[]) => {
  if (formRef.value) {
    formRef.value.clearValidate(props)
  }
}

// 滚动到指定字段
const scrollToField = (prop: string) => {
  if (formRef.value) {
    formRef.value.scrollToField(prop)
  }
}

// 事件处理函数
const handleValidate = (isValid: boolean, fields: any) => {
  emit('validate', isValid, fields)
}

const handleSubmit = async () => {
  if (props.validateOnSubmit) {
    const isValid = await validate()
    if (!isValid) return
  }

  emit('submit', props.modelValue)
}

const handleReset = () => {
  resetFields()
}

// 暴露表单方法给父组件
defineExpose({
  validate,
  validateField,
  resetFields,
  clearValidate,
  scrollToField,
  formRef
})
</script>

<style scoped>
.base-form {
  width: 100%;
}

.base-form__actions {
  display: flex;
  justify-content: flex-end;
  gap: var(--dbu-space-3);
  margin-top: var(--dbu-space-6);
  padding-top: var(--dbu-space-4);
  border-top: 1px solid var(--dbu-border-light);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .base-form__actions {
    flex-direction: column;
    gap: var(--dbu-space-2);
  }

  .base-form__actions .el-button {
    width: 100%;
  }
}

/* 内联表单样式调整 */
.base-form:deep(.el-form--inline) .base-form__actions {
  margin-top: 0;
  padding-top: 0;
  border-top: none;
  margin-left: var(--dbu-space-4);
}
</style>